import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:get/get.dart';
import 'package:ride_rex/article/detail/article_detail_page.dart';
import 'package:ride_rex/generated/assets.dart';
import 'package:ride_rex/main/discover/discover_bean.dart';
import 'package:ride_rex/person_detail/person_detail_logic.dart';
import 'package:ride_rex/person_detail/person_detail_page.dart';
import 'package:ride_rex/route.dart';
import 'package:ride_rex/standard/app_colors.dart';
import 'package:ylm_ui_kit/ylm_ui_kit.dart';

import 'discover_logic.dart';

class DiscoverPage extends StatefulWidget {
  const DiscoverPage(this.logic, {Key? key}) : super(key: key);

  final DiscoverLogic logic;

  @override
  State<DiscoverPage> createState() => _DiscoverPageState();
}

class _DiscoverPageState extends State<DiscoverPage> with AutomaticKeepAliveClientMixin {
  @override
  void initState() {
    super.initState();
    widget.logic.initData();
  }

  @override
  Widget build(BuildContext context) {
    super.build(context);
    return const _DiscoverPage();
  }

  @override
  bool get wantKeepAlive => true;
}

class _DiscoverPage extends GetView<DiscoverLogic> {
  const _DiscoverPage();

  @override
  Widget build(BuildContext context) {
    return BaseScaffold(
      hideBackBtn: true,
      child: Stack(
        alignment: Alignment.topCenter,
        children: [
          _buildBg().positioned(top: 0, left: 0, right: 0, bottom: 0),
          Column(
            children: [
              _buildTitle().padding(top: ScreenUtil().statusBarHeight),
              Expanded(child: _buildListView().paddingTop(10.w)),
            ],
          ),
        ],
      ),
    );
  }

  Widget _buildBg() => Container(decoration: BoxDecoration(gradient: AppColors.primaryGradient));

  Widget _buildTitle() => IconWidget.image(Assets.pngDiscoverTitle, width: 189.w, height: 43.w);

  Widget _buildListView() => GetBuilder<DiscoverLogic>(
        init: DiscoverLogic(),
        builder: (logic) {
          return ListView.separated(
            padding: EdgeInsets.symmetric(horizontal: 16.w),
            itemCount: logic.list.length,
            itemBuilder: (context, index) {
              return _DiscoverItem(logic.list[index]);
            },
            separatorBuilder: (BuildContext context, int index) => CommonMargin.height(16.w),
          );
        },
      );
}

class _DiscoverItem extends StatelessWidget {
  const _DiscoverItem(this.bean);

  final FeedUserBean bean;

  @override
  Widget build(BuildContext context) {
    return ButtonWidget(
      onTap: () {
        FeedUserWorkBean? workBean;
        if (bean.works != null && bean.works!.isNotEmpty) {
          workBean = bean.works!.first;
        }
        if (workBean == null) return;
        CommonRoute.open(ArticleDetailPage(bean, workBean));
      },
      hasInkWell: false,
      child: Container(
        decoration: CommonDecoration.getShapeDecoration(radius: 12.w, bg: '#E0FEF6'.toColor),
        child: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Stack(
              children: [
                _buildImage(),
                _buildMore().positioned(right: 12.w, top: 12.w),
              ],
            ),
            _buildTitle().padding(top: 8.w, left: 12.w, right: 12.w),
            _buildContent().padding(top: 6.w, left: 12.w, right: 12.w),
            Row(
              children: [
                Stack(
                  children: [
                    _buildAvatar(),
                    if (!(bean.isFriend ?? false)) _buildAdd().positioned(right: 0, bottom: 0),
                  ],
                ),
                _buildNickName().paddingHorizontal(8.w).expanded(),
                _buildPraiseBtn().paddingRight(12.w),
              ],
            ).padding(top: 8.w, left: 12.w, right: 12.w, bottom: 10.w),
          ],
        ),
      ),
    );
  }

  Widget _buildImage() {
    String path = '';
    if ((bean.works ?? []).isNotEmpty) path = bean.works!.first.cover ?? '';
    return path.empty
        ? const SizedBox()
        : FractionallySizedBox(
            widthFactor: 1,
            child: AspectRatio(
              aspectRatio: 1.78,
              child: ImageWidget.asset(
                'assets/ride_rex_images/$path',
                fit: BoxFit.cover,
                radius: 12.w,
              ),
            ),
          );
  }

  Widget _buildMore() => ButtonWidget.icon(
        IconWidget.image(
          Assets.pngDiscoverMore,
          size: 28.w,
        ),
        hasInkWell: false,
        onTap: () => CommonLogic.onTapMore(bean.userId ?? '', showFollow: bean.isFriend == false),
      );

  Widget _buildTitle() {
    String title = '';
    if ((bean.works ?? []).isNotEmpty) title = bean.works!.first.title ?? '';
    return TextWidget.oneLine(
      text: title,
      fontSize: 16,
      color: '#202020'.toColor,
    );
  }

  Widget _buildContent() {
    String description = '';
    if ((bean.works ?? []).isNotEmpty) description = bean.works!.first.description ?? '';
    return TextWidget.moreLine(
      text: description,
      fontSize: 14,
      color: Colors.black.withOpacity(0.8),
    );
  }

  Widget _buildAvatar() => ButtonWidget(
        onTap: () => CommonRoute.open(PersonDetailPage(bean)),
        hasInkWell: false,
        child: ImageWidget.url(
          bean.avatar ?? '',
          width: 42.w,
          height: 42.w,
          radius: 42.w,
          fit: BoxFit.cover,
        ),
      );

  Widget _buildAdd() => ButtonWidget.icon(
        IconWidget.image(
          Assets.pngDiscoverAdd,
          size: 16.w,
        ),
        hasInkWell: false,
        onTap: () async {
          if (bean.userId.empty) return;
          Loading.show();
          await CommonLogic.follow(bean.userId!);
          Loading.toast('Follow success', closeLoading: true);
        },
      );

  Widget _buildNickName() => TextWidget.oneLine(
        text: bean.nickname ?? '',
        fontSize: 16,
        color: '#202020'.toColor,
      );

  Widget _buildPraiseBtn() {
    bool isLike = false;
    String workId = '';
    if (bean.works != null && bean.works!.isNotEmpty) {
      isLike = bean.works!.first.isLike == '1';
      workId = bean.works!.first.workId ?? '';
    }
    return ButtonWidget.icon(
      IconWidget.image(
        isLike ? Assets.pngDiscoverPraiseSelect : Assets.pngDiscoverPraiseNormal,
        size: 34.w,
      ),
      hasInkWell: false,
      onTap: () {
        if (workId.empty) return;
        if (isLike) {
          CommonLogic.cancelLike(recordId: workId);
        } else {
          CommonLogic.like(recordId: workId);
        }
      },
    );
  }
}
